$(document).ready(function(){
	var tagShow = new TagsShow("#tagsShow", "#PostTags");
	var datePicker = new DatePicker(".date", "#PostAddForm");
});

function TagsShow(selStr, selPost){
	this.$tagsShow = $(selStr);
	this.$post = $(selPost);
	this.$tokenSpan = this.$tagsShow.children("span");
	this.$tokens = this.$tokenSpan.children();
	this.$input = this.$tagsShow.children("#inputEditor");
	this.init();
}

TagsShow.prototype = {
	init : function(){
		
		var _this = this;
		
		this.initPost();
		
		// about edit and new
		this.$tagsShow.click(function(){
			_this.$input.focus();
		});
		
		this.$input.blur(function(){
			_this.confirmPost();
		});
		
		
		if ($.browser.mozilla) {
			// to work in ff
			// about delete
			this.$input.keypress(function(event){
				if (event.keyCode == 13) {
					_this.confirmPost();
					return false;
				}
				if (event.keyCode == 8) {
					if ($(this).val() == "") {
						// remove the last tag
						_this.$tokenSpan.children(":last").remove();
						
					// remove last tag string from post input
						_this.deleteTag();
					}
				}
				
			});
		}else{
			// to work in IE7+
			this.$input.keydown(function(event){
				// 8 means the enter key
				if (event.keyCode == 8) {
					if ($(this).val() == "") {
						// remove the last tag
						_this.$tokenSpan.children(":last").remove();
						
					// remove last tag string from post input
						_this.deleteTag();
					}
				}
			});
			
			// to work in IE6
			this.$input.keypress(function(event){
				// 13 means the delete key
				if (event.keyCode == 13) {
					_this.confirmPost();
					return false;
				}
			})
		}

		this.$tokens.children("a").click(function(){
			var index = $(this).parent().index();
			$(this).parent().remove();
			_this.deleteTag(index);
			return false;
		});
	},

	confirmPost : function(){
		
		var text = this.trim(this.$input.val());
		if (this.validateInput(text)) {
			this.$tokenSpan.children(".lastTagToken").removeClass("lastTagToken");
			this.insertNewTag(text);
			this.$input.val("");
		}else{
			this.$input.val("");
		}
	},
	
	/**
	 * insert a new tag
	 * @param {Object} text
	 */
	insertNewTag : function(text){
		var _this = this;
		// append token to tokens
		var $removeBtn = $('<a title="Remove tag" href="#">x</a>');
		// bind click event
		$removeBtn.click(function(){
			var index = $(this).parent().index();
			$(this).parent().remove();
			_this.deleteTag(index);
			return false;
		});
		var $newToken = $('<div class="token"><span>'+text+'</span></div>');
		$newToken.append($removeBtn);
//		this.$tokenSpan.append($newToken);
		_this.$tokenSpan.append($newToken);
		
		
		
		// append token to post input
		var postText = this.$post.val();
		if (postText == "") {
			this.$post.val(this.$post.val() + text);
		}else{
			this.$post.val(this.$post.val() + "," + text);
		}
	},
	
	initPost : function(){
		var $spans = this.$tokens.children("span");
		var subArray = new Array();
		$.each($spans, function(index, span){
			subArray[index] = $(span).text();
		});
		var length = subArray.length;
		if (length > 0) {
			var newStr = subArray[0]
			for (var i = 1; i < length; i++) {
				newStr += "," + subArray[i];
			}
			this.$post.val(newStr);
		}
	},
	
	deleteTag : function(index){
		_this = this;
		var subArray = this.$post.val().split(",");
		var newStr = "";
		var length = subArray.length;
		if(!index){
			index = length -1;
		}
		for(var i=0; i<length; i++){
			if(i != index){
				if (newStr == "") {
					newStr += subArray[i];
				}else{
					newStr += ","+subArray[i];
			}
		}
		this.$post.val(newStr);
	}
		
	},
	
	/**
	 * make sure input is not empty string
	 * @param {Object} text
	 */
	validateInput : function(text){
		if (text == "") {
			return false;
		}else{
			return true;
		}
	},
	
	trim : function(str) {  
    	return str.replace(/(^\s*)|(\s*$)/g, "");  
	} 
	
}


function DatePicker(selStr, formStr){
	var _this = this;
	this.$input = $(selStr);
	var $form = $(formStr);
	this.$input.datepicker();
	this.$input.datepicker( "option", "dateFormat", "yy-mm-dd" );
	this.$input.val("now");
	$form.submit(function(){
		var date = _this.$input.val();
		if(date == "now"){
			_this.$input.val((new Date()).format("yyyy-MM-dd hh:mm:ss"));
		}else{
			_this.$input.val((new Date(date)).format("yyyy-MM-dd hh:mm:ss"));
		}
		//alert(_this.$input.val());
	});
}


Date.prototype.format = function(format) {  
    /* 
     * eg:format="yyyy-MM-dd hh:mm:ss"; 
     */  
    var o = {  
        "M+" : this.getMonth() + 1, // month  
        "d+" : this.getDate(), // day  
        "h+" : this.getHours(), // hour  
        "m+" : this.getMinutes(), // minute  
        "s+" : this.getSeconds(), // second  
        "q+" : Math.floor((this.getMonth() + 3) / 3), // quarter  
        "S" : this.getMilliseconds()  
        // millisecond  
    }  
  
    if (/(y+)/.test(format)) {  
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4  
                        - RegExp.$1.length));  
    }  
  
    for (var k in o) {  
        if (new RegExp("(" + k + ")").test(format)) {  
            format = format.replace(RegExp.$1, RegExp.$1.length == 1  
                            ? o[k]  
                            : ("00" + o[k]).substr(("" + o[k]).length));  
        }  
    }  
    return format;  
}  



















